package org.racsor.cc.action;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.racsor.cc.model.PMF;
import org.racsor.cc.model.RequestCC;

import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

@SuppressWarnings("serial")
public class DoProcess extends HttpServlet {
    private static final Logger log = Logger.getLogger(DoProcess.class.getName());
    String content = "application/x-amf";
    URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();

    public void doGet(HttpServletRequest req, HttpServletResponse resp) {

	try {
	    String id = (String) req.getParameter("id");
	    if (StringUtils.isEmpty(id)) {
		id = "5";
	    }
	    log.warning("id:" + id);

	    PersistenceManager pm = PMF.get().getPersistenceManager();

	    Query query = pm.newQuery(RequestCC.class);
	    query.setFilter("frecuency == frequencia");
	    query.setOrdering("sortorder desc");
	    query.declareParameters("String frequencia");

	    try {
		ProcessRequestCC pr = new ProcessRequestCC();
		@SuppressWarnings("unchecked")
		List<RequestCC> results = (List<RequestCC>) query.execute(id);
		if (!results.isEmpty()) {
		    for (RequestCC requestcc : results) {
			pr.doProcess(requestcc);
			pm.makePersistent(requestcc);
		    }
		} else {
		    log.warning("query no results");
		}
	    } finally {
		query.closeAll();
		pm.close();
	    }

	    RequestDispatcher dispatcher = req.getRequestDispatcher("WEB-INF/jsp/requestcc.jsp");
	    dispatcher.forward(req, resp);
	} catch (Exception e) {
	    log.warning(ExceptionUtils.getStackTrace(e));
	}

    }

}
